package com.doc.controller;

import com.doc.entity.MyFileInfo;
import com.doc.service.ViewFile;
import com.doc.websocket.service.WebSocketServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Controller
public class IndexController {

    private final ViewFile viewFile;


    public IndexController(ViewFile viewFile) {
        this.viewFile = viewFile;;
    }

    /**
     * 初始化方法
     *
     * @return index页面
     */
    @RequestMapping("index.do")
    public String index() {
        return "index";
    }

    /**
     * 测试页面
     *
     * @return 测试webSocket
     */
    @RequestMapping("test.do")
    public String testWebSocket() {
        return "testWebSocket";
    }
    /**
     * 查询
     *
     * @return 文件信息数据
     */
    @RequestMapping("viewFile.do")
    @ResponseBody
    public HashMap<String, Object> viewFile(MyFileInfo myFileInfo) throws Exception {
        return viewFile.viewFile(myFileInfo);
    }

    /**
     * 文件路径下文件路径
     * @param myFileInfo 文件路径
     * @return 入参下的文件路径
     */
    @RequestMapping("viewPath.do")
    @ResponseBody
    public List<MyFileInfo> viewPath(MyFileInfo myFileInfo){
        ArrayList<MyFileInfo> myFileInfos = new ArrayList<>();
        File file = new File(myFileInfo.getFilePath());

        if(file.exists()){
            if(file.isFile()|| Objects.requireNonNull(file.list()).length==0){
                myFileInfos.add(myFileInfo);
            }else {
                for (String path : Objects.requireNonNull(file.list())) {
                    MyFileInfo fileInfo = new MyFileInfo();
                    if(myFileInfo.getFilePath().endsWith(File.separator)){
                        fileInfo.setFilePath(myFileInfo.getFilePath()+path);
                    }else {
                        fileInfo.setFilePath(myFileInfo.getFilePath()+File.separator+path);
                    }
                    myFileInfos.add(fileInfo);
                }
            }
        }
        return myFileInfos;
    }

}
